package com.lenovo.newsapp.parser;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.lenovo.newsapp.R;
import com.lenovo.newsapp.activity.LoginActivity;
import com.lenovo.newsapp.model.Comment;
import com.lenovo.newsapp.model.CurrentColumnId;
import com.lenovo.newsapp.model.HomeNews;
import com.lenovo.newsapp.model.ImageDetail;
import com.lenovo.newsapp.model.ReadCategory;
import com.lenovo.newsapp.util.Const;
import com.lenovo.newsapp.util.HttpUtil;
import com.lenovo.newsapp.util.PreferenceUtil;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLProcedureInvocationData;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.WLResponseListener;

public class InfoJSONParser {

	protected static JSONObject jsonObj;
	public static ArrayList<HomeNews> getInfoList(int pageNo,String usercode,int flag,Context context) throws Exception {
		
		String url="";
		if(Const.currentSection == 0){
			url=Const.DOMAIN+"/Webservice/newsList?catalog=home&page="+pageNo+"&pageNum="+Const.PAGE_SIZE+"&category_id="+PreferenceUtil.getInt("checkedRadioBtn",0);
		}else if(Const.currentSection == 1){
			url=Const.DOMAIN+"/Webservice/newsList?catalog=banner&page="+pageNo+"&pageNum="+Const.PAGE_SIZE+"&category_id="+PreferenceUtil.getInt("checkedRadioBtn",0);
		}else if(Const.currentSection == 2){
			url=Const.DOMAIN+"/Webservice/newsList?catalog=recent&page="+pageNo+"&pageNum="+Const.PAGE_SIZE+"&category_id="+PreferenceUtil.getInt("checkedRadioBtn",0);
			
		}else if(Const.currentSection == 3){
			url=Const.DOMAIN+"/Webservice/newsList?catalog=gallery&page="+pageNo+"&pageNum="+Const.PAGE_SIZE+"&category_id="+PreferenceUtil.getInt("checkedRadioBtn",0);
			
		}else if(Const.currentSection == 7){
//			http://localhost:9000/Webservice/collectList?usercode=rong&page=1&pageNum=10
			url=Const.DOMAIN+"/Webservice/collectList?usercode="+usercode+"&page="+pageNo+"&pageNum="+Const.PAGE_SIZE+"&category_id="+PreferenceUtil.getInt("checkedRadioBtn",0);
			
		}else if(Const.currentSection == 5){
			url=Const.DOMAIN+"/Webservice/newsList?catalog=email&page="+pageNo+"&pageNum="+Const.PAGE_SIZE+"&category_id="+PreferenceUtil.getInt("checkedRadioBtn",0);
		}
		JSONObject jsonObj = null;
		String offline = PreferenceUtil.getString(Const.OFFLINE, "open");
		Log.v(Const.DEBUG, "offline--" + offline);
		Log.v(Const.DEBUG, "url--" + url);
//		if (HttpUtil.isNetworkAvailable(context)) {
//
//			jsonObj = HttpUtil.getJSONObjFromUrlByGet(url, false);
//			if (flag == Const.INIT_FLAG || flag == Const.REFRESH_FLAG) {
//				PreferenceUtil.commitString(Const.SAVENEWS + ""
//						+ Const.currentSection, jsonObj.toString());
//			}
//		} else {
//			if (flag == Const.INIT_FLAG || flag == Const.REFRESH_FLAG) {
//				jsonObj = new JSONObject(PreferenceUtil.getString(
//						Const.SAVENEWS + "" + Const.currentSection, null));
//			} else {
//				jsonObj = null;
//			}
//		}
		String offLineNews = PreferenceUtil.getString(Const.SAVENEWS + "" + Const.currentSection, null);
		Log.v("dddd-", Const.SAVENEWS + "" + Const.currentSection);
//		Log.v("dddd", offLineNews);
		if(null != offLineNews && !offLineNews.equals("") &&Const.manuallyRefresh == false && pageNo == 1){
			Log.v("dddd", "使用离线数据");
				jsonObj = new JSONObject(PreferenceUtil.getString(
						Const.SAVENEWS + "" + Const.currentSection, null));
		}else{
			Log.v("dddd", "在线数据获取");
			if (!HttpUtil.isNetworkAvailable(context)) {
				Toast.makeText(context, R.string.can_not_connect_server,
						Toast.LENGTH_SHORT).show();
			}else{
				
				jsonObj = HttpUtil.getJSONObjFromUrlByGet(url, false);
				if(pageNo == 1){
					
					PreferenceUtil.commitString(Const.SAVENEWS + ""
							+ Const.currentSection, jsonObj.toString());
				}
			}
		}
 
		
//		Log.v(Const.DEBUG, "getInfoList = " + jsonObj);
		int statusCode = jsonObj.getInt(Const.STATUS);
		JSONArray resultListArray = jsonObj.getJSONArray(Const.RESULT);
		ArrayList<HomeNews> resultList = new ArrayList<HomeNews>();
		if (statusCode == 0) {
			for (int i = 0; i < resultListArray.length(); i++) {

				JSONObject r = resultListArray.getJSONObject(i);

				HomeNews homeNews = new HomeNews();
				homeNews.setNewsId(r.getInt("news_id"));
				homeNews.setTitle(r.getString("title"));
				homeNews.setSummary(r.getString("summary"));
				homeNews.setNewsThumbnail(r.getString("title_icon_url"));
				homeNews.setAuthor(r.getString("author"));
				homeNews.setKeyword(r.getString("keyword"));
				homeNews.setLastUpdateTime(r.getString("last_update_time"));
				homeNews.setImgFrist(r.getString("file_one"));
				homeNews.setImgSecend(r.getString("file_two"));
				homeNews.setImgThird(r.getString("file_three"));
				homeNews.setImgSize(r.getString("img_size"));
				resultList.add(homeNews);
			}
		}
		Const.manuallyRefresh = false;
		return resultList;
	}

	public static HomeNews getGalleriesNewDetail(String id,Context context,int flag) throws Exception {
//		JSONObject jsonObj = HttpUtil.getJSONObjFromUrlByGet(Const.DOMAIN+"/Webservice/newsDtail?id="+id+"&usercode="+PreferenceUtil.getString("username", ""), false);
		String url = Const.DOMAIN+"/Webservice/newsDtail?id="+id+"&usercode="+PreferenceUtil.getString("username", "");
		//JSONObject jsonObj = HttpUtil.getJSONObjFromUrlByGet(Const.DOMAIN+"/Webservice/newsDtail?id=11", false);
		Log.v(Const.DEBUG, "getGalleriesNewDetail = " + Const.DOMAIN+"/Webservice/newsDtail?id="+id+"&usercode="+PreferenceUtil.getString("username", ""));
//		Log.v(Const.DEBUG, "getGalleriesNewDetail = " + jsonObj);

	//	int statusCode = jsonObj.getInt(Const.STATUS);
//		JSONObject  r = jsonObj.getJSONObject(Const.RESULT);
		
//		if (HttpUtil.isNetworkAvailable(context)) {
//			jsonObj = HttpUtil.getJSONObjFromUrlByGet(url, false);
//				PreferenceUtil.commitString(Const.SAVE_NEWS_DETAIL + ""+ id, jsonObj.toString());
//		} else {
//			jsonObj = new JSONObject(PreferenceUtil.getString(Const.SAVE_NEWS_DETAIL + "" + id, null));
//		}
		String offNewsDetail = PreferenceUtil.getString(Const.SAVE_NEWS_DETAIL + "" + id, null);
		if(null != offNewsDetail && !offNewsDetail.equals("") && Const.manuallyRefresh == false){
			jsonObj = new JSONObject(PreferenceUtil.getString(Const.SAVE_NEWS_DETAIL + "" + id, null));
//			Log.v(Const.DEBUG, "本地数据 = " + jsonObj);
		} else {
			if (!HttpUtil.isNetworkAvailable(context)) {
				Toast.makeText(context, R.string.can_not_connect_server,
						Toast.LENGTH_SHORT).show();
			}else{
				jsonObj = HttpUtil.getJSONObjFromUrlByGet(url, false);
				PreferenceUtil.commitString(Const.SAVE_NEWS_DETAIL + "" + id,
						jsonObj.toString());
//				Log.v(Const.DEBUG, "在线数据 = " + jsonObj);
			}
		}
		
//		Log.v("dd", "detail = " + jsonObj);
		
		JSONObject  r = jsonObj.getJSONObject(Const.RESULT);

		//图片
		JSONArray resultListArray = r.getJSONArray("news_attachment");
		ArrayList<ImageDetail> l = new ArrayList<ImageDetail>();

			for (int i = 0; i < resultListArray.length(); i++) {
				
				JSONObject p = resultListArray.getJSONObject(i);
				ImageDetail image = new ImageDetail();
				image.setUrl(p.getString("url"));
				l.add(image);
		}



		HomeNews homeNews = new HomeNews();

		homeNews.setNewsId(r.getInt("news_id"));
		homeNews.setTitle(r.getString("title"));
		homeNews.setContent(r.getString("content"));
		homeNews.setAuthor(r.getString("author"));
		homeNews.setKeyword(r.getString("keyword"));
		homeNews.setImageDetailList(l);
		homeNews.setLastUpdateTime(r.getString("last_update_time"));
		homeNews.setLike(r.getInt("like"));
		homeNews.setCollect(r.getInt("collect"));
		homeNews.setLikeCount(r.getInt("like_count"));
		homeNews.setCommentCount(r.getInt("comment_count"));
		
		Log.v("xx", "id = " + id+",like_count = " +r.getInt("like_count") +",comment_count = " +r.getInt("comment_count"));
		Const.manuallyRefresh = false;
		return homeNews;
	}

	public static ArrayList<HomeNews> getInfoListForWL(JSONObject jsonObj) throws Exception {
//		JSONObject jsonObj = getInfo(pageNo);
//		Log.v(Const.DEBUG, "getInfoList = " + jsonObj);
		int statusCode = jsonObj.getInt(Const.STATUS);
		JSONArray resultListArray = jsonObj.getJSONArray(Const.RESULT);
		ArrayList<HomeNews> resultList = new ArrayList<HomeNews>();
		if (statusCode == 0) {
			for (int i = 0; i < resultListArray.length(); i++) {

				JSONObject r = resultListArray.getJSONObject(i);

				HomeNews homeNews = new HomeNews();
				homeNews.setNewsId(r.getInt("news_id"));
				homeNews.setTitle(r.getString("title"));
				homeNews.setSummary(r.getString("summary"));
				homeNews.setNewsThumbnail(r.getString("title_icon_url"));
				homeNews.setAuthor(r.getString("author"));
				homeNews.setKeyword(r.getString("keyword"));
				homeNews.setLastUpdateTime(r.getString("last_update_time"));
				homeNews.setImgFrist(r.getString("file_one"));
				homeNews.setImgSecend(r.getString("file_two"));
				homeNews.setImgThird(r.getString("file_three"));
				resultList.add(homeNews);
			}
		}
		return resultList;
	}

	public static JSONObject getInfo(int pageNo) {
		String adapterName = "NewsAppAdapter";
		String procedureName = "getNewsList";
		WLProcedureInvocationData invocationData = new WLProcedureInvocationData(
				adapterName, procedureName);

		Log.v(Const.DEBUG, "catalog=gallery&currentPage = " + pageNo
				+ ",pageNum = " + Const.PAGE_SIZE);
		Object[] parameters = new Object[] { "gallery", pageNo + "",
				"" + Const.PAGE_SIZE };
		invocationData.setParameters(parameters);

		LoginActivity.client = WLClient.getInstance();
		LoginActivity.client.invokeProcedure(invocationData,
				new WLResponseListener() {

					public void onSuccess(WLResponse response) {
						jsonObj = response.getResponseJSON();
//						Log.v(Const.DEBUG, "onSuccess--dataJson = " + jsonObj);
					}

					public void onFailure(WLFailResponse response) {
						String responseText = response.getResponseText();
						Log.v(Const.DEBUG, "onFailure-responseText="
								+ responseText);
					}

				}, null);
//		Log.v(Const.DEBUG, "dataJson = " + jsonObj);
		return jsonObj;
	}
	//Comment
	public static ArrayList<Comment> getCommentList(int news_id, int pageNo) throws Exception {
		//测试接口
		JSONObject jsonObj = HttpUtil.getJSONObjFromUrlByGet(
				Const.DOMAIN+"/Webservice/commentsList?news_id="+news_id+"&page="+pageNo+"&pageNum="+Const.PAGE_SIZE+"&usercode="+PreferenceUtil.getString("username", ""), false);
		
		Log.v("comment url------>", ""+Const.DOMAIN+"/Webservice/commentsList?news_id="+news_id+"&page="+pageNo+"&pageNum="+Const.PAGE_SIZE+"&usercode="+PreferenceUtil.getString("username", ""));
//		Log.v("comment------>", ""+jsonObj);
		int statusCode = jsonObj.getInt(Const.STATUS);
		JSONArray resultListArray = jsonObj.getJSONArray(Const.RESULT);
		ArrayList<Comment> resultList = new ArrayList<Comment>();
		if (statusCode == 0) {
			for (int i = 0; i < resultListArray.length(); i++) {
				
				JSONObject r = resultListArray.getJSONObject(i);
	
				Comment comment = new Comment();
	//测试
				comment.setCommentId(r.getInt("comment_id"));
				comment.setCommentContent(r.getString("comment_text"));
//				comment.setCommentNumber(r.getInt("like_count"));
				comment.setLastUpdateTime(r.getString("comment_timestamp"));
				comment.setUpsNumber(r.getInt("like_count"));
				comment.setUserName(r.getString("comment_page_owner"));
				comment.setIsLike(r.getInt("like_usercode"));
				
//				comment.setCommentContent(r.getString("commentContent"));
//				comment.setCommentNumber(r.getInt("commentNumber"));
//				comment.setLastUpdateTime(r.getString("lastUpdateTime"));
//				comment.setUpsNumber(r.getInt("upsNumber"));
//				comment.setUserName(r.getString("userName"));
//				comment.setUserId(r.getInt("userId"));

				resultList.add(comment);
			}
		}
		return resultList;
	}
	
	
	public static ArrayList<HomeNews> getDetailWL(String id) throws Exception{
		Log.v(Const.DEBUG,"detail--");
		final ArrayList<HomeNews> resultList = new ArrayList<HomeNews>();
		String adapterName = "NewsAppAdapter";
		String procedureName = "getNewsDetail";
		WLProcedureInvocationData invocationData = new WLProcedureInvocationData(
				adapterName, procedureName);

		Object[] parameters = new Object[] { id,};
		invocationData.setParameters(parameters);

		LoginActivity.client = WLClient.getInstance();
		LoginActivity.client.invokeProcedure(invocationData,
				new WLResponseListener() {

					public void onSuccess(WLResponse response) {
						jsonObj = response.getResponseJSON();
						JSONObject r;
						try {
							r = jsonObj.getJSONObject(Const.RESULT);
							//图片
							JSONArray resultListArray = r.getJSONArray("news_attachment");
							Log.v(Const.DEBUG, "p---> = " + resultListArray);
							ArrayList<ImageDetail> l = new ArrayList<ImageDetail>();

								for (int i = 0; i < resultListArray.length(); i++) {
									
									JSONObject p = resultListArray.getJSONObject(i);
									ImageDetail image = new ImageDetail();
									image.setUrl(p.getString("url"));
									l.add(image);
							}

						


							HomeNews homeNews = new HomeNews();

							homeNews.setNewsId(r.getInt("news_id"));
							homeNews.setTitle(r.getString("title"));
							homeNews.setContent(r.getString("content"));
							homeNews.setAuthor(r.getString("author"));
							homeNews.setKeyword(r.getString("keyword"));
							homeNews.setImageDetailList(l);
							homeNews.setLastUpdateTime(r.getString("last_update_time"));
							resultList.add(homeNews);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						

						
					}

					public void onFailure(WLFailResponse response) {
						String responseText = response.getResponseText();
						Log.v(Const.DEBUG, "onFailure-responseText="
								+ responseText);
					}

				}, null);
		Log.v(Const.DEBUG, "resultList.size()---> = " + resultList.size());
		
		return resultList;
	}
	
	public static ArrayList<ReadCategory> getCategoryList(){

		
		String adapterName = "NewsAppAdapter";
		String procedureName = "categoryList";
		WLProcedureInvocationData invocationData = new WLProcedureInvocationData(
				adapterName, procedureName);
		Object[] parameters = new Object[] {};
		invocationData.setParameters(parameters);

		LoginActivity.client = WLClient.getInstance();
		LoginActivity.client.invokeProcedure(invocationData,
				new WLResponseListener() {

					public void onSuccess(WLResponse response) {
						final JSONObject jsonObj = response.getResponseJSON();
//						Log.v(Const.DEBUG, "onSuccess--dataJson = " + jsonObj);
//						int statusCode = jsonObj.getInt(Const.STATUS);
//						JSONArray resultListArray = jsonObj.getJSONArray(Const.RESULT);
//						ArrayList<ReadCategory> resultList = new ArrayList<ReadCategory>();

					}

					public void onFailure(WLFailResponse response) {
						String responseText = response.getResponseText();
						Log.v(Const.DEBUG, "onFailure--responseText = " + responseText);
					}

				}, null);
		return null;
	
	}
	
	public static ArrayList<CurrentColumnId> getCurrentColumnIdList(){

		String catalog = "home";
		if(Const.currentSection == 0){
			catalog = "home";
		}else if(Const.currentSection == 1){
			catalog = "banner";
		}else if(Const.currentSection == 2){
			catalog = "recent";
		}else if(Const.currentSection == 3){
			catalog = "gallery";
		}else if(Const.currentSection == 7){
			catalog = "favorite";
		}else if(Const.currentSection == 5){
			catalog = "email";
		}
		
		final ArrayList<CurrentColumnId> resultList = new ArrayList<CurrentColumnId>();
		
		String adapterName = "NewsAppAdapter";
		String procedureName = "newsListid";
		WLProcedureInvocationData invocationData = new WLProcedureInvocationData(
				adapterName, procedureName);
		Object[] parameters = new Object[] {catalog,PreferenceUtil.getInt("checkedRadioBtn",0)+"",PreferenceUtil.getString("username", "")};
		invocationData.setParameters(parameters);

		LoginActivity.client = WLClient.getInstance();
		LoginActivity.client.invokeProcedure(invocationData,
				new WLResponseListener() {

					public void onSuccess(WLResponse response) {
						final JSONObject jsonObj = response.getResponseJSON();
//						Log.v(Const.DEBUG, "onSuccess--dataJson = " + jsonObj);
						
						int statusCode;
						try {
							statusCode = jsonObj.getInt(Const.STATUS);
							JSONArray resultListArray = jsonObj.getJSONArray(Const.RESULT);
							
							if (statusCode == 0) {
								for (int i = 0; i < resultListArray.length(); i++) {
									
									JSONObject r = resultListArray.getJSONObject(i);
									
									CurrentColumnId currentColumnIds = new CurrentColumnId();
									currentColumnIds.setNewsId(r.getInt("NEWS_ID"));
									resultList.add(currentColumnIds);
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
//						return resultList;

					}

					public void onFailure(WLFailResponse response) {
						String responseText = response.getResponseText();
						Log.v(Const.DEBUG, "onFailure--responseText = " + responseText);
					}

				}, null);
		return resultList;
	
	}
	
}